package com.hghivln.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hghivln.blog.common.lang.Result;
import com.hghivln.blog.entity.Music;
import com.hghivln.blog.mapper.MusicMapper;
import com.hghivln.blog.pojo.dto.MusicDto;
import com.hghivln.blog.pojo.vo.MusicVo;
import com.hghivln.blog.service.MusicService;
import com.hghivln.blog.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 歌曲表 服务实现类
 * </p>
 *
 * @author hghivln
 * @since 2021-09-16
 */
@Service
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music> implements MusicService {

    @Override
    public void deleteById(Long id) {
        getBaseMapper().delById(id);

    }

    @Override
    public MusicVo getInfo(Long id) {
        QueryWrapper<Music> qw = new QueryWrapper<>();
        qw.eq("id", id);
        Music music = getBaseMapper().selectOne(qw);
        MusicVo musicVo = new MusicVo();
        BeanUtils.copyProperties(music, musicVo);
        musicVo.setFileName(musicVo.getArtist()+"-"+musicVo.getName()+".mp3");
        return musicVo;
    }

    @Override
    public void updateByMId(MusicDto musicDto) {
        Music music = new Music();
        BeanUtils.copyProperties(musicDto, music);
        getBaseMapper().updateById(music);
    }

    @Override
    public void toggleEnable(MusicDto musicDto) {
        Music music = new Music();
        BeanUtils.copyProperties(musicDto, music);
        getBaseMapper().updateEnable(music);
    }

    @Override
    public Result<?> loadAllMusic(MusicDto musicDto) {
        Page<Music> page = new Page<>(musicDto.getPage(),musicDto.getLimit());
        QueryWrapper<Music> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(musicDto.getName()), "name", musicDto.getName());
        qw.eq(musicDto.getEnable() != null, "enable", musicDto.getEnable());
        qw.eq("deleted", 0);
        qw.orderByDesc("created_time");
        qw.select("id", "name", "artist", "url", "cover", "lrc", "created_time", "enable");
        getBaseMapper().selectPage(page, qw);
        return new Result<>(page.getTotal(), page.getRecords());
    }

    @Override
    public void saveMusic(MusicDto musicDto) {
        Music music = new Music();
        BeanUtils.copyProperties(musicDto, music);
        System.out.println(music);
        getBaseMapper().insert(music);
    }

    @Override
    public List<Music> getAllEnable() {
        QueryWrapper<Music> qw = new QueryWrapper<>();
        qw.eq("enable",1);
        qw.eq("deleted",0);
        return getBaseMapper().selectList(qw);
    }
}
